from rest_framework.views import APIView
from apps.coffee.serializers.coffee_serializer import CoffeeDetailSerializer, CoffeeSerializer
from utils.response import ApiResponse
from apps.coffee.models import coffee,category
from django.db.models import Sum
# 新增：导入缓存模块
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page

# 新增 导入分页模块
from django.core.paginator import Paginator

@method_decorator(cache_page(600), name='dispatch')
class HomeView(APIView):
  def get_statistics(request):
    """
    获取统计数据
    """
    coffee_count = coffee.objects.count()
    category_count = category.objects.count()
    views_count = coffee.objects.aggregate(views_count=Sum('views'))['views_count']
    likes_count = coffee.objects.aggregate(likes_count=Sum('likes'))['likes_count']
    return ApiResponse(
      message='获取统计数据成功',
      data={
      'coffee': coffee_count,
      'category': category_count,
      'views': views_count,
      'likes': likes_count
    })
  # 获取咖啡列表接口
  def get_coffee_list(request):
    queryset = coffee.objects.all()

    # 接收参数
    order_by = request.GET.get('orderby','id')
    status = request.GET.get('status',0)
    pageSize = request.GET.get('page_size',10)
    page = request.GET.get('page',1)

    filter_params = {}
    # 拼接排序方式
    ordering = f'{"-"}{order_by}'
    # 获取筛选参数
    if status == '1':
      filter_params = {'status':1}
    # 判断排序参数
    if order_by == 'recommend':
      filter_params = {'recommend': 1}
      ordering = f'{"-"}{"id"}'
    # 查询数据
    queryset = queryset.filter(**filter_params).order_by(ordering)
    #创建分页器
    paginator = Paginator(queryset,pageSize)
    coffeeObj = paginator.get_page(page)
    coffee_list = CoffeeSerializer(coffeeObj,many=True).data

    result = {
      'data': coffee_list,
      'page':int(page),
      'page_size':int(pageSize),
      'total':queryset.count()
    }
    return ApiResponse(message="获取coffee数据列表成功",data=result)
  
  def get_coffee_detail(request, pk):
    try:
      coffee_instance = coffee.objects.get(pk=pk)
      return ApiResponse(
        code=200,
          message='success', 
          data=CoffeeDetailSerializer(coffee_instance).data)
    except coffee.DoesNotExist:
      return ApiResponse(code=404, message='数据不存在')
  
  def set_coffee_like(request, pk):
    try:
      coffee_instance = coffee.objects.get(pk=pk)
      coffee_instance.likes = coffee_instance.likes + 1
      coffee_instance.save()
      return ApiResponse(
        code=200,
          message='success', 
          data=CoffeeSerializer(coffee_instance).data)
    except coffee.DoesNotExist:
      return ApiResponse(code=404, message='数据不存在')
    
  def set_coffee_view(request, pk):
    try:
      coffee_instance = coffee.objects.get(pk=pk)
      coffee_instance.views = coffee_instance.views + 1
      coffee_instance.save()
      return ApiResponse(
        code=200,
          message='success', 
          data=CoffeeSerializer(coffee_instance).data)
    except coffee.DoesNotExist:
      return ApiResponse(code=404, message='数据不存在')

